package com.iwhalecloud.bss.kite.cucc.service.attr;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.ztesoft.bss.common.util.SpringUtil;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Objects;
import java.util.Optional;

/**
 * @Description :类似雁飞格物DMP平台--公有化商品，计算总的结算价和销售价，可以使用该类
 * @Author : xie.zhengjun
 * @Date : 2022/01/11 11:29
 */
public class OrderModelCalculateHelper {

    private static final String FIELD_NAME_SUM_SETTLE_PRICE = "210008139";

    public static void calculateSettlePrice(KiteAttr attr, KiteInst inst, AttrData data) {
        //订购模式
        KiteAttr orderModelAttr = getKiteAttr(attr, inst, "210008072");
        //订购年限
        KiteAttr yearAttr = getKiteAttr(attr, inst, "210008134");
        //结算价折扣率
        KiteAttr discountRateAttr = getKiteAttr(attr, inst, "210008073");
        //N1档次-（0-1000]/D1结算价格（万元）
        KiteAttr settlePriceAttr_N1 = inst.getAttr("210008080");
        //N2档次-（1000-2000]/D2结算价格（万元）
        KiteAttr settlePriceAttr_N2 = inst.getAttr("210008082");
        //N3档次-（2000-3000]/D3结算价格（万元）
        KiteAttr settlePriceAttr_N3 = inst.getAttr("210008084");

        //D1档次-(0,9000]结算价格（元）
        KiteAttr settlePriceAttr_D1 = inst.getAttr("210008074");
        //D2档次-(9000,60000]结算价格（元）
        KiteAttr settlePriceAttr_D2 = inst.getAttr("210008076");
        //D3档次-(60000, 720000]结算价格
        KiteAttr settlePriceAttr_D3 = inst.getAttr("210008078");

        if(Objects.nonNull(orderModelAttr) && Objects.nonNull(discountRateAttr)){
            String orderModelVal = orderModelAttr.getValue();
            String discountRateVal = discountRateAttr.getValue();
            String orderYear = "--请选择--";
            if (Objects.nonNull(yearAttr) && KiteStringUtils.isNotEmpty(yearAttr.getValue()) && KiteStringUtils.equalsAny(yearAttr.getShowType(), KeyConsts.PROD_ATTR_SHOW_TYPE_D, KeyConsts.PROD_ATTR_SHOW_TYPE_M)) {
                orderYear = yearAttr.getValueDesc();
            }
            //订购模式为包年服务N1档次
            if(KiteStringUtils.isEqual(orderModelVal, "110015093")){
                String settlePriceVal = Optional.ofNullable(settlePriceAttr_N1).map(KiteAttr::getDefaultValue).orElse("");
                if (KiteStringUtils.isNotEmpty(discountRateVal)) {
                    settlePriceVal = calcPriceByDiscount(settlePriceVal, discountRateVal);
                }
                String allSettlePrice = OrderModelCalculateHelper.getResultSa(settlePriceVal, orderYear);
                modAttrValue(inst, "210008080", settlePriceVal, data.getSceneInstId());
                modAttrValue(inst, FIELD_NAME_SUM_SETTLE_PRICE, allSettlePrice, data.getSceneInstId());
            }
            //订购模式为包年服务N2档次
            else if (KiteStringUtils.isEqual(orderModelVal, "110015094")) {
                String settlePriceVal = Optional.ofNullable(settlePriceAttr_N2).map(KiteAttr::getDefaultValue).orElse("");
                if (KiteStringUtils.isNotEmpty(discountRateVal)) {
                    settlePriceVal = calcPriceByDiscount(settlePriceVal, discountRateVal);
                }
                String allSettlePrice = OrderModelCalculateHelper.getResultSa(settlePriceVal, orderYear);
                modAttrValue(inst, "210008082", settlePriceVal, data.getSceneInstId());
                modAttrValue(inst, FIELD_NAME_SUM_SETTLE_PRICE, allSettlePrice, data.getSceneInstId());
            }
            //订购模式为包年服务N3档次
            else if (KiteStringUtils.isEqual(orderModelVal, "110015095")) {
                String settlePriceVal = Optional.ofNullable(settlePriceAttr_N3).map(KiteAttr::getDefaultValue).orElse("");
                if (KiteStringUtils.isNotEmpty(discountRateVal)) {
                    settlePriceVal = calcPriceByDiscount(settlePriceVal, discountRateVal);
                }
                String allSettlePrice = OrderModelCalculateHelper.getResultSa(settlePriceVal, orderYear);
                modAttrValue(inst, "210008084", settlePriceVal, data.getSceneInstId());
                modAttrValue(inst, FIELD_NAME_SUM_SETTLE_PRICE, allSettlePrice, data.getSceneInstId());
            }
            //订购模式为按量计费
            else if (KiteStringUtils.isEqual(orderModelVal, "100000157")) {
                String settlePriceValD1 = Optional.ofNullable(settlePriceAttr_D1).map(KiteAttr::getDefaultValue).orElse("");
                String settlePriceValD2 = Optional.ofNullable(settlePriceAttr_D2).map(KiteAttr::getDefaultValue).orElse("");
                String settlePriceValD3 = Optional.ofNullable(settlePriceAttr_D3).map(KiteAttr::getDefaultValue).orElse("");
                if (KiteStringUtils.isNotEmpty(discountRateVal)) {
                    settlePriceValD1 = calcPriceByDiscount(settlePriceValD1, discountRateVal);
                    settlePriceValD2 = calcPriceByDiscount(settlePriceValD2, discountRateVal);
                    settlePriceValD3 = calcPriceByDiscount(settlePriceValD3, discountRateVal);
                }
                modAttrValue(inst, "210008074", settlePriceValD1, data.getSceneInstId());
                modAttrValue(inst, "210008076", settlePriceValD2, data.getSceneInstId());
                modAttrValue(inst, "210008078", settlePriceValD3, data.getSceneInstId());
            }
        }
    }

    public static String getResultLpa(String lpa, String discountRate, String orderYear) {
        //当结算价折扣率不为空时，计算折扣
        if (KiteStringUtils.isNotEmpty(lpa) && KiteStringUtils.isNotEmpty(discountRate) && !KiteStringUtils.isEqual(orderYear,"--请选择--")) {
            BigDecimal lpa_n = new BigDecimal(lpa);
            BigDecimal discountRate_n = new BigDecimal(discountRate);
            BigDecimal orderYear_n = new BigDecimal(orderYear);
            BigDecimal result_lpa_n = lpa_n.multiply(discountRate_n);
            double result_lpa = result_lpa_n.multiply(orderYear_n).doubleValue();
            DecimalFormat df = new DecimalFormat();
            df.applyPattern("0.000");
            return doubleTrans(df.format(result_lpa / 100));
        } else if (KiteStringUtils.isNotEmpty(lpa) && KiteStringUtils.isEmpty(discountRate) && !KiteStringUtils.isEqual(orderYear,"--请选择--")) {
            //当结算价折扣率为空时，总结算价不需要计算折扣
            BigDecimal lpa_n = new BigDecimal(lpa);
            BigDecimal orderYear_n = new BigDecimal(orderYear);
            double result_lpa = lpa_n.multiply(orderYear_n).doubleValue();
            DecimalFormat df = new DecimalFormat();
            df.applyPattern("0.000");
            return doubleTrans(df.format(result_lpa));
        }
        return null;
    }

    public static String getResultSa(String sa, String orderYear) {
        if(KiteStringUtils.isNotEmpty(sa)  && !KiteStringUtils.isEqual(orderYear,"--请选择--")) {
            BigDecimal sa_n = new BigDecimal(sa);
            BigDecimal orderYear_n = new BigDecimal(orderYear);
            double result_sa = sa_n.multiply(orderYear_n).doubleValue();
            DecimalFormat df = new DecimalFormat();
            df.applyPattern("0.000");
            return doubleTrans(df.format(result_sa));
        }
        return null;
    }

    public static String calcPriceByDiscount(String price, String discountRate) {
        if(KiteStringUtils.isNotEmpty(price) && KiteStringUtils.isNotEmpty(discountRate)) {
            BigDecimal p = new BigDecimal(price);
            BigDecimal d = new BigDecimal(discountRate);
            double result = p.multiply(d).doubleValue();
            DecimalFormat df = new DecimalFormat();
            df.applyPattern("0.000");
            return doubleTrans(df.format(result / 100));
        }
        return null;
    }


    /**
     * Double处理小数点
     * @param d
     * @return
     */
    public static String doubleTrans(String d){
        double num = Double.valueOf(d);
        if(Math.abs(Math.round(num) - num) < 0.000001){
            return String.valueOf((long)num);
        }
        return String.valueOf(num);
    }

    private static void modAttrValue(KiteInst inst, String fieldName, String value, String sceneInstId) {
        SpringUtil.getBean(OperateInstAttrService.class).setAttrValue(inst, fieldName, value, sceneInstId, null);
    }

    private static KiteAttr getKiteAttr(KiteAttr attr, KiteInst inst, String fieldName) {
        KiteAttr result;
        if (KiteStringUtils.equals(attr.getFieldName(), fieldName)) {
            result = attr;
        } else {
            result = inst.getAttr(fieldName);
        }
        return result;
    }
}
